﻿using Asxsyd92Core.Utils;
using Asxsyd92Core.Utils.Provider;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using WebOS.Dal;
using WebOS.Modle;
using WebOS.Modle.WorkFlowCustomEventParams;
using WebOS.Modle.WorkFlowExecute;
using WebOS.Modle.WorkFlowInstalledSub;

namespace WebOS.Bll
{
    public class WorkFlowTaskBll
    {
        private WorkFlow bWorkFlow = new WorkFlow();
        WebOS.Modle.WorkFlowRun.RunJSON wfInstalled;
        // private WorkFlowInstalled wfInstalled;
        private Result result;
        private List<WorkFlowTask> nextTasks = new List<WorkFlowTask>();
        public static WorkFlowTaskBll Instance
        {
            get { return SingletonProvider<WorkFlowTaskBll>.Instance; }
        }

        public string WaitList(object p, string title, Guid type, Guid user, DateTime date1, DateTime date2, int page, int limit)
        {
            throw new NotImplementedException();
        }


        /// <summary>
        /// 获取待办
        /// </summary>
        /// <param name="guid">当前用户</param>
        /// <param name="title">标题</param>
        /// <param name="type">流程id</param>
        /// <param name="user">发送者</param>
        /// <param name="date1">开始时间</param>
        /// <param name="date2">结束时间</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public string WaitList(Guid guid, string title, Guid type, Guid user, DateTime date1, DateTime date2, int page, int limit)
        {
            string counts = "(select count(1) from WorkFlowTask where Status in(0,1) and ReceiveID='" + guid + "' ";
            string sqls = "", f = "";
            string sql = "";
            if (type != null && type != Guid.Empty)
            {

                sql = sql + "  and FlowID= '" + type + "'";
                counts = counts + "  and FlowID ='" + type + "'";
                f = f + "  and FlowID ='" + type + "'";
            }
            if (title != "" && title != null)
            {
                title = "'%" + title + "%'";
                sql = sql + " and Title like " + title;
                counts = counts + " and Title like " + title;
                f = f + " and Title like " + title;
            }

            //降序
            sql = sql + "and RowNumber > " + limit + " * (" + page + " - 1)";
            //分页
            var fy = "(SELECT ROW_NUMBER() OVER(ORDER BY id DESC) AS RowNumber,*FROM WorkFlowTask where  Status in(0,1) and ReceiveID='" + guid + "' " + f + ")";
            sqls = "select top " + limit + "  *," + counts + ") as Count  from " + fy + " as A where  Status in(0,1) and ReceiveID='" + guid + "' " + sql;
            var da = WorkFlowTaskDal.Instance.GetList(sqls, new { }).ToList();

            return JSONhelper.ToJson(new { code = 0, msg = "", count = da.Count == 0 ? 0 : da.First().Count, data = da }, false);
        }

        public string TasksDetail(string instanceID, Guid userid, Guid flowID, Guid stepID, string Table)
        {
            var da = WorkFlowTaskDal.Instance.GetWhere(new { instanceID = instanceID, ReceiveID = userid, flowID = flowID }).FirstOrDefault();


            var ksa = "";//Asxsyd92Core.Utils.Data.DbUtils.GetNoMoldeWhere<object>(Table, new { id = da.InstanceID }).ToList();

            return JSONhelper.ToJson(new { code = 0, msg = "", count = 1, data = da, ywdata = ksa }, false);


        }

        /// <summary>
        /// 获取已办
        /// </summary>
        /// <param name="guid">当前用户</param>
        /// <param name="title">标题</param>
        /// <param name="type">流程id</param>
        /// <param name="user">发送者</param>
        /// <param name="date1">开始时间</param>
        /// <param name="date2">结束时间</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public string CompletedList(Guid guid, string title, Guid type, Guid user, DateTime date1, DateTime date2, int page, int limit)
        {
            string counts = "(select count(1) from WorkFlowTask where Status in(2,3,4,5,6) and ReceiveID='" + guid + "'";
            string sqls = "", f = "";
            string sql = "";
            if (type != null && type != Guid.Empty)
            {

                sql = sql + "  and FlowID= '" + type + "'";
                counts = counts + "  and FlowID ='" + type + "'";
                f = f + "  and FlowID ='" + type + "'";
            }
            if (title != "" && title != null)
            {
                title = "'%" + title + "%'";
                sql = sql + " and Title like " + title;
                counts = counts + " and Title like " + title;
                f = f + " and Title like " + title;
            }

            //降序
            sql = sql + "and RowNumber > " + limit + " * (" + page + " - 1)";
            //分页
            var fy = "(SELECT ROW_NUMBER() OVER(ORDER BY id DESC) AS RowNumber,*FROM WorkFlowTask where  Status in(2,3,4,5,6) and ReceiveID='" + guid + "'" + f + ")";
            sqls = "select top " + limit + "  *," + counts + ") as Count  from " + fy + " as A where  Status in(2,3,4,5,6) and ReceiveID='" + guid + "' " + sql;
            var da = WorkFlowTaskDal.Instance.GetList(sqls, new { }).ToList();

            return JSONhelper.ToJson(new { code = 0, msg = "", count = da.Count == 0 ? 0 : da.First().Count, data = da }, false);
        }


        /// <summary>
        /// 执行自定义方法
        /// </summary>
        /// <param name="eventName"></param>
        /// <returns></returns>
        public object ExecuteFlowCustomEvent(string eventName, object eventParams, string dllName = "")
        {
            if (dllName.IsNullOrEmpty())
            {
                dllName = eventName.Substring(0, eventName.IndexOf('.'));
            }
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(dllName);
            string typeName = System.IO.Path.GetFileNameWithoutExtension(eventName);
            string methodName = eventName.Substring(typeName.Length + 1);
            Type type = assembly.GetType(typeName, true);

            object obj = System.Activator.CreateInstance(type, false);
            var method = type.GetMethod(methodName);

            if (method != null)
            {
                return method.Invoke(obj, new object[] { eventParams });
            }
            else
            {
                throw new MissingMethodException(typeName, methodName);
            }
        }



        /// <summary>
        /// 处理流程
        /// </summary>
        /// <param name="executeModel">处理实体</param>
        /// <returns></returns>
        public Result Execute(Execute executeModel)
        {
            result = new Result();
            nextTasks = new List<WorkFlowTask>();
            if (executeModel.FlowID == Guid.Empty)
            {
                result.DebugMessages = "流程ID错误";
                result.IsSuccess = false;
                result.Messages = "执行参数错误";
                return result;
            }

            var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(executeModel.FlowID);
            string error = "";
            wfInstalled = wfl.runjson;// WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);
                                      // wfInstalled = bWorkFlow.GetWorkFlowRunModel(executeModel.FlowID);
            if (wfInstalled == null)
            {
                result.DebugMessages = "未找到流程运行时实体";
                result.IsSuccess = false;
                result.Messages = "流程运行时为空";
                return result;
            }

            lock (executeModel.GroupID.ToString())
            {
                switch (executeModel.ExecuteType)
                {
                    case EnumType.ExecuteType.Back:
                        executeBack(executeModel);
                        break;

                    case EnumType.ExecuteType.Save:
                        executeSave(executeModel);
                        break;
                    case EnumType.ExecuteType.Submit:
                    case EnumType.ExecuteType.Completed:
                        executeSubmit(executeModel);
                        break;
                    case EnumType.ExecuteType.Redirect:
                        executeRedirect(executeModel);
                        break;
                    default:
                        result.DebugMessages = "流程处理类型为空";
                        result.IsSuccess = false;
                        result.Messages = "流程处理类型为空";
                        return result;
                }

                result.NextTasks = nextTasks;
                return result;
            }
        }


        private void executeSubmit(Execute executeModel)
        {
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                //如果是第一步提交并且没有实例则先创建实例
                WorkFlowTask currentTask = null;
                bool isFirst = executeModel.StepID == wfInstalled.FirstStepID && executeModel.TaskID == Guid.Empty && executeModel.GroupID == Guid.Empty;
                if (isFirst)
                {
                    currentTask = createFirstTask(executeModel);
                }
                else
                {
                    currentTask = WorkFlowTaskDal.Instance.Get(executeModel.TaskID);
                }
                if (currentTask == null)
                {
                    result.DebugMessages = "未能创建或找到当前任务";
                    result.IsSuccess = false;
                    result.Messages = "未能创建或找到当前任务";
                    return;
                }
                else if (currentTask.Status.In(2, 3, 4, 5))
                {
                    result.DebugMessages = "当前任务已处理";
                    result.IsSuccess = false;
                    result.Messages = "当前任务已处理";
                    return;
                }

                var currentSteps = wfInstalled.steps.Where(p => p.id == executeModel.StepID.ToString());
                var currentStep = currentSteps.Count() > 0 ? currentSteps.First() : null;
                if (currentStep == null)
                {
                    result.DebugMessages = "未找到当前步骤";
                    result.IsSuccess = false;
                    result.Messages = "未找到当前步骤";
                    return;
                }

                //如果当前步骤是子流程步骤，并且策略是 子流程完成后才能提交 则要判断子流程是否已完成
                if (currentStep.type == "subflow"
                    && currentStep.subflow.IsGuid()
                    && currentStep.behavior.subflowstrategy == "0"
                    && currentTask.SubFlowGroupID.HasValue
                    && !currentTask.SubFlowGroupID.Value.IsEmptyGuid()
                    && !GetInstanceIsCompleted(currentStep.subflow.ToGuid(), currentTask.SubFlowGroupID.Value))
                {
                    result.DebugMessages = "当前步骤的子流程实例未完成,子流程：" + currentStep.subflow + ",实例组：" + currentTask.SubFlowGroupID.ToString();
                    result.IsSuccess = false;
                    result.Messages = "当前步骤的子流程未完成,不能提交!";
                    return;
                }

                //如果是完成任务或者没有后续处理步骤，则完成任务
                if (executeModel.ExecuteType == EnumType.ExecuteType.Completed
                    || executeModel.Steps == null || executeModel.Steps.Count == 0)
                {
                    executeComplete(executeModel);
                    scope.Complete();
                    return;
                }

                int status = 0;

                #region 处理策略判断
                if (currentTask.StepID != wfInstalled.FirstStepID)//第一步不判断策略
                {
                    switch (currentStep.behavior.hanlderModel.ToInt32())
                    {
                        case 0://所有人必须处理
                            var taskList = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                            if (taskList.Count > 1)
                            {
                                var noCompleted = taskList.Where(p => p.Status != 2);
                                if (noCompleted.Count() - 1 > 0)
                                {
                                    status = -1;
                                }
                            }
                            Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign);
                            break;
                        case 1://一人同意即可
                            var taskList1 = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                            foreach (var task in taskList1)
                            {
                                if (task.ID != currentTask.ID)
                                {
                                    if (task.Status.In(0, 1))
                                    {
                                        Completed(task.ID, "", false, 4);
                                    }
                                }
                                else
                                {
                                    Completed(task.ID, executeModel.Comment, executeModel.IsSign);
                                }
                            }
                            break;
                        case 2://依据人数比例
                            var taskList2 = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                            if (taskList2.Count > 1)
                            {
                                decimal percentage = currentStep.behavior.percentage.ToInt32() <= 0 ? 100 : currentStep.behavior.percentage.ToInt32();//比例
                                if ((((decimal)(taskList2.Where(p => p.Status == 2).Count() + 1) / (decimal)taskList2.Count) * 100).Round() < percentage)
                                {
                                    status = -1;
                                }
                                else
                                {
                                    foreach (var task in taskList2)
                                    {
                                        if (task.ID != currentTask.ID && task.Status.In(0, 1))
                                        {
                                            Completed(task.ID, "", false, 4);
                                        }
                                    }
                                }
                            }
                            Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign);
                            break;
                        case 3://独立处理
                            Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign);
                            break;
                    }
                }
                else
                {
                    Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign);
                }
                #endregion

                //如果条件不满足则创建一个状态为-1的后续任务，等条件满足后才修改状态，待办人员才能看到任务。
                if (status == -1)
                {
                    var tempTasks = createTempTasks(executeModel, currentTask);
                    List<string> nextStepName = new List<string>();
                    foreach (var nstep in tempTasks)
                    {
                        nextStepName.Add(nstep.StepName);
                    }
                    nextTasks.AddRange(tempTasks);
                    string stepName = nextStepName.Distinct().ToArray().Join1(",");
                    result.DebugMessages += string.Format("已发送到:{0},其他人未处理,不创建后续任务", stepName);
                    result.IsSuccess = true;
                    result.Messages += string.Format("已发送到:{0},等待他人处理!", stepName);
                    result.NextTasks = nextTasks;
                    scope.Complete();
                    return;
                }

                foreach (var step in executeModel.Steps)
                {
                    foreach (var user in step.Value)
                    {
                        if (wfInstalled == null) //子流程有多个人员时此处会为空，所以判断并重新获取
                        {
                            var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(executeModel.FlowID);
                            string error = "";
                            wfInstalled = wfl.runjson;//WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);
                        }
                        var nextSteps = wfInstalled.steps.Where(p => p.id == step.Key.ToString());
                        if (nextSteps.Count() == 0)
                        {
                            continue;
                        }
                        var nextStep = nextSteps.First();

                        bool isPassing = 0 == nextStep.behavior.countersignature.ToInt32();

                        #region 如果下一步骤为会签，则要检查当前步骤的平级步骤是否已处理
                        if (0 != nextStep.behavior.countersignature.ToInt32())
                        {
                            var prevSteps = WorkFlowBll.Instance.GetPrevSteps(executeModel.FlowID, nextStep.id.ToGuid());
                            switch (nextStep.behavior.countersignature.ToInt32())
                            {
                                case 1://所有步骤同意
                                    isPassing = true;
                                    foreach (var prevStep in prevSteps)
                                    {
                                        if (!IsPassing(prevStep, executeModel.FlowID, executeModel.GroupID, currentTask.PrevID, currentTask.Sort))
                                        {
                                            isPassing = false;
                                            break;
                                        }
                                    }
                                    break;
                                case 2://一个步骤同意即可
                                    isPassing = false;
                                    foreach (var prevStep in prevSteps)
                                    {
                                        if (IsPassing(prevStep, executeModel.FlowID, executeModel.GroupID, currentTask.PrevID, currentTask.Sort))
                                        {
                                            isPassing = true;
                                            break;
                                        }
                                    }
                                    break;
                                case 3://依据比例
                                    int passCount = 0;
                                    foreach (var prevStep in prevSteps)
                                    {
                                        if (IsPassing(prevStep, executeModel.FlowID, executeModel.GroupID, currentTask.PrevID, currentTask.Sort))
                                        {
                                            passCount++;
                                        }
                                    }
                                    isPassing = (((decimal)passCount / (decimal)prevSteps.Count) * 100).Round() >= (nextStep.behavior.countersignaturePercentage.ToInt32() <= 0 ? 100 : nextStep.behavior.countersignaturePercentage.ToInt32());
                                    break;
                            }
                            if (isPassing)
                            {
                                var tjTasks = GetTaskList(currentTask.ID, false);
                                foreach (var tjTask in tjTasks)
                                {
                                    if (tjTask.ID == currentTask.ID || tjTask.Status.In(2, 3, 4, 5))
                                    {
                                        continue;
                                    }
                                    Completed(tjTask.ID, "", false, 4);
                                }
                            }
                        }
                        #endregion

                        if (isPassing)
                        {
                            WorkFlowTask task = new WorkFlowTask();
                            if (nextStep.workTime != "")
                            {
                                double gs; double.TryParse(nextStep.workTime, out gs);
                                task.CompletedTime = DateTime.Now.AddHours(gs);
                            }

                            task.FlowID = executeModel.FlowID;
                            task.GroupID = currentTask != null ? currentTask.GroupID : executeModel.GroupID;
                            task.ID = Guid.NewGuid();
                            task.Type = 0;
                            task.InstanceID = executeModel.InstanceID;
                            if (!executeModel.Note.IsNullOrEmpty())
                            {
                                task.Note = executeModel.Note;
                            }
                            task.PrevID = currentTask.ID;
                            task.PrevStepID = currentTask.StepID;
                            task.ReceiveID = user.ID;
                            task.ReceiveName = user.Name;
                            task.ReceiveTime = DateTime.Now;
                            task.SenderID = executeModel.Sender.ID;
                            task.SenderName = executeModel.Sender.Name;
                            task.SenderTime = task.ReceiveTime;
                            task.Status = status;
                            task.StepID = step.Key;
                            task.StepName = nextStep.name;
                            task.Sort = currentTask.Sort + 1;
                            task.Title = executeModel.Title.IsNullOrEmpty() ? currentTask.Title : executeModel.Title;
                            task.Urls = currentTask.Urls;
                            #region 如果当前步骤是子流程步骤，则要发起子流程实例
                            if (nextStep.type == "subflow" && nextStep.subflow.IsGuid())
                            {
                                Execute subflowExecuteModel = new Execute();
                                if (!nextStep.events.submitBefore.IsNullOrEmpty())
                                {
                                    object obj = ExecuteFlowCustomEvent(nextStep.events.submitBefore.Trim(),
                                        new WorkFlowCustomEventParams()
                                        {
                                            FlowID = executeModel.FlowID,
                                            GroupID = currentTask.GroupID,
                                            InstanceID = currentTask.InstanceID,
                                            StepID = executeModel.StepID,
                                            TaskID = currentTask.ID
                                        });
                                    if (obj is Execute)
                                    {
                                        subflowExecuteModel = obj as Execute;
                                    }
                                }
                                subflowExecuteModel.ExecuteType = EnumType.ExecuteType.Save;
                                subflowExecuteModel.FlowID = nextStep.subflow.ToGuid();
                                subflowExecuteModel.Sender = user;
                                if (subflowExecuteModel.Title.IsNullOrEmpty())
                                {
                                    subflowExecuteModel.Title = "未命名的任务";
                                }
                                if (subflowExecuteModel.InstanceID.IsNullOrEmpty())
                                {
                                    subflowExecuteModel.InstanceID = "";
                                }
                                var subflowTask = createFirstTask(subflowExecuteModel, true);
                                task.SubFlowGroupID = subflowTask.GroupID;
                            }
                            #endregion

                            if (!HasNoCompletedTasks(executeModel.FlowID, step.Key, currentTask.GroupID, user.ID))
                            {
                                WorkFlowTaskDal.Instance.Insert(task);
                            }
                            nextTasks.Add(task);
                            WorkFlowTaskDal.Instance.Insert(task);
                        }
                    }

                }

                if (nextTasks.Count > 0)
                {
                    //激活临时任务
                    UpdateTempTasks(nextTasks.First().FlowID, nextTasks.First().StepID, nextTasks.First().GroupID,
                         nextTasks.First().CompletedTime, nextTasks.First().ReceiveTime);

                    #region 抄送
                    if (wfInstalled == null)
                    {
                        var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(executeModel.FlowID);
                        string error = "";
                        var wfInstalled = WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);

                    }
                    foreach (var step in executeModel.Steps)
                    {
                        var nextSteps = wfInstalled.steps.Where(p => p.id == step.Key.ToString());
                        if (nextSteps.Count() > 0)
                        {
                            var nextStep = nextSteps.First();
                            if (!nextStep.behavior.copyFor.IsNullOrEmpty())
                            {
                                var users = OrganizeBll.Instance.GetAllUsers(nextStep.behavior.copyFor);
                                foreach (var user in users)
                                {
                                    WorkFlowTask task = new WorkFlowTask();
                                    if (nextStep.workTime != "")
                                    {
                                        double gs; double.TryParse(nextStep.workTime, out gs);
                                        task.CompletedTime = DateTime.Now.AddHours(gs);
                                    }
                                    task.FlowID = executeModel.FlowID;
                                    task.GroupID = currentTask != null ? currentTask.GroupID : executeModel.GroupID;
                                    task.ID = Guid.NewGuid();
                                    task.Type = 5;
                                    task.InstanceID = executeModel.InstanceID;
                                    task.Note = executeModel.Note.IsNullOrEmpty() ? "抄送任务" : executeModel.Note + "(抄送任务)";
                                    task.PrevID = currentTask.ID;
                                    task.PrevStepID = currentTask.StepID;
                                    task.ReceiveID = user.ID;
                                    task.ReceiveName = user.Name;
                                    task.ReceiveTime = DateTime.Now;
                                    task.SenderID = executeModel.Sender.ID;
                                    task.SenderName = executeModel.Sender.Name;
                                    task.SenderTime = task.ReceiveTime;
                                    task.Status = status;
                                    task.StepID = step.Key;
                                    task.StepName = nextStep.name;
                                    task.Sort = currentTask.Sort + 1;
                                    task.Title = executeModel.Title.IsNullOrEmpty() ? currentTask.Title : executeModel.Title;
                                    if (!HasNoCompletedTasks(executeModel.FlowID, step.Key, currentTask.GroupID, user.ID))
                                    {
                                        WorkFlowTaskDal.Instance.Insert(task);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    List<string> nextStepName = new List<string>();
                    foreach (var nstep in nextTasks)
                    {
                        nextStepName.Add(nstep.StepName);
                    }
                    string stepName = nextStepName.Distinct().ToArray().Join1(",");
                    result.DebugMessages += string.Format("已发送到:{0}", stepName);
                    result.IsSuccess = true;
                    result.Messages += string.Format("已发送到:{0}", stepName);
                    result.NextTasks = nextTasks;
                }
                else
                {
                    var tempTasks = createTempTasks(executeModel, currentTask);
                    List<string> nextStepName = new List<string>();
                    foreach (var nstep in tempTasks)
                    {
                        nextStepName.Add(nstep.StepName);
                    }
                    nextTasks.AddRange(tempTasks);
                    string stepName = nextStepName.Distinct().ToArray().Join1(",");
                    result.DebugMessages += string.Format("已发到:{0},等待其它步骤处理", stepName);
                    result.IsSuccess = true;
                    result.Messages += string.Format("已发送:{0},等待其它步骤处理", stepName);
                    result.NextTasks = nextTasks;
                }
                scope.Complete();
            }
        }

        /// <summary>
        /// 退回任务
        /// </summary>
        /// <param name="executeModel"></param>
        private void executeBack(Execute executeModel)
        {
            var currentTask = WorkFlowTaskDal.Instance.Get(executeModel.TaskID);
            if (currentTask == null)
            {
                result.DebugMessages = "未能找到当前任务";
                result.IsSuccess = false;
                result.Messages = "未能找到当前任务";
                return;
            }
            else if (currentTask.Status.In(2, 3, 4, 5))
            {
                result.DebugMessages = "当前任务已处理";
                result.IsSuccess = false;
                result.Messages = "当前任务已处理";
                return;
            }

            var currentSteps = wfInstalled.steps.Where(p => p.id == currentTask.StepID.ToString());
            var currentStep = currentSteps.Count() > 0 ? currentSteps.First() : null;

            if (currentStep == null)
            {
                result.DebugMessages = "未能找到当前步骤";
                result.IsSuccess = false;
                result.Messages = "未能找到当前步骤";
                return;
            }
            if (currentTask.StepID == wfInstalled.FirstStepID)
            {
                result.DebugMessages = "当前任务是流程第一步,不能退回";
                result.IsSuccess = false;
                result.Messages = "当前任务是流程第一步,不能退回";
                return;
            }
            if (executeModel.Steps.Count == 0)
            {
                result.DebugMessages = "没有选择要退回的步骤";
                result.IsSuccess = false;
                result.Messages = "没有选择要退回的步骤";
                return;
            }
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                List<WorkFlowTask> backTasks = new List<WorkFlowTask>();
                int status = 0;
                switch (currentStep.behavior.backModel.ToInt32())
                {
                    case 0://不能退回
                        result.DebugMessages = "当前步骤设置为不能退回";
                        result.IsSuccess = false;
                        result.Messages = "当前步骤设置为不能退回";
                        return;
                    #region 根据策略退回
                    case 1:
                        switch (currentStep.behavior.hanlderModel.ToInt32())
                        {
                            case 0://所有人必须同意,如果一人不同意则全部退回
                                var taskList = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                                foreach (var task in taskList)
                                {
                                    if (task.ID != currentTask.ID)
                                    {
                                        if (task.Status.In(0, 1))
                                        {
                                            Completed(task.ID, "", false, 5);
                                            //backTasks.Add(task);
                                        }
                                    }
                                    else
                                    {
                                        Completed(task.ID, executeModel.Comment, executeModel.IsSign, 3);
                                    }
                                }
                                break;
                            case 1://一人同意即可
                                var taskList1 = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                                if (taskList1.Count > 1)
                                {
                                    var noCompleted = taskList1.Where(p => p.Status != 3);
                                    if (noCompleted.Count() - 1 > 0)
                                    {
                                        status = -1;
                                    }
                                }
                                Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign, 3);
                                break;
                            case 2://依据人数比例
                                var taskList2 = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort && p.Type != 5);
                                if (taskList2.Count > 1)
                                {
                                    decimal percentage = currentStep.behavior.percentage.ToInt32() <= 0 ? 100 : currentStep.behavior.percentage.ToInt32();//比例
                                    if ((((decimal)(taskList2.Where(p => p.Status == 3).Count() + 1) / (decimal)taskList2.Count) * 100).Round() < 100 - percentage)
                                    {
                                        status = -1;
                                    }
                                    else
                                    {
                                        foreach (var task in taskList2)
                                        {
                                            if (task.ID != currentTask.ID && task.Status.In(0, 1))
                                            {
                                                Completed(task.ID, "", false, 5);
                                                //backTasks.Add(task);
                                            }
                                        }
                                    }
                                }
                                Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign, 3);
                                break;
                            case 3://独立处理
                                Completed(currentTask.ID, executeModel.Comment, executeModel.IsSign, 3);
                                break;
                        }
                        WorkFlowTaskDal.Instance.Insert(currentTask);
                        break;
                        #endregion
                }

                if (status == -1)
                {
                    result.DebugMessages += "已退回,等待他人处理";
                    result.IsSuccess = true;
                    result.Messages += "已退回,等待他人处理!";
                    result.NextTasks = nextTasks;
                    scope.Complete();
                    return;
                }

                foreach (var backTask in backTasks)
                {
                    if (backTask.Status.In(2, 3))//已完成的任务不能退回
                    {
                        continue;
                    }
                    if (backTask.ID == currentTask.ID)
                    {
                        Completed(backTask.ID, executeModel.Comment, executeModel.IsSign, 3);
                    }
                    else
                    {
                        Completed(backTask.ID, "", false, 3, "他人已退回");
                    }
                }

                List<WorkFlowTask> tasks = new List<WorkFlowTask>();
                if (currentStep.behavior.hanlderModel.ToInt32().In(0, 1, 2))//退回时要退回其它步骤发来的同级任务。
                {
                    var tjTasks = GetTaskList(currentTask.FlowID, currentTask.StepID, currentTask.GroupID).FindAll(p => p.Sort == currentTask.Sort);
                    foreach (var tjTask in tjTasks)
                    {
                        if (!executeModel.Steps.ContainsKey(tjTask.PrevStepID))
                        {
                            executeModel.Steps.Add(tjTask.PrevStepID, new List<Users>());
                        }
                    }
                }
                foreach (var step in executeModel.Steps)
                {
                    var tasks1 = GetTaskList(executeModel.FlowID, step.Key, executeModel.GroupID);
                    if (tasks1.Count > 0)
                    {
                        tasks1 = tasks1.OrderByDescending(p => p.Sort).ToList();
                        int maxSort = tasks1.First().Sort;
                        tasks.AddRange(tasks1.FindAll(p => p.Sort == maxSort));
                    }
                }

                #region 处理会签形式的退回
                //当前步骤是否是会签步骤
                var countersignatureStep = WorkFlowBll.Instance.GetNextSteps(executeModel.FlowID, executeModel.StepID).Find(p => p.Behavior.Countersignature != 0);
                bool IsCountersignature = countersignatureStep != null;
                bool isBack = true;
                if (IsCountersignature)
                {
                    var steps = WorkFlowBll.Instance.GetPrevSteps(executeModel.FlowID, countersignatureStep.ID);
                    switch (countersignatureStep.Behavior.Countersignature)
                    {
                        case 1://所有步骤处理，如果一个步骤退回则退回
                            isBack = false;
                            foreach (var step in steps)
                            {
                                if (IsBack(step, executeModel.FlowID, currentTask.GroupID, currentTask.PrevID, currentTask.Sort))
                                {
                                    isBack = true;
                                    break;
                                }
                            }
                            break;
                        case 2://一个步骤退回,如果有一个步骤同意，则不退回
                            isBack = true;
                            foreach (var step in steps)
                            {
                                if (!IsBack(step, executeModel.FlowID, currentTask.GroupID, currentTask.PrevID, currentTask.Sort))
                                {
                                    isBack = false;
                                    break;
                                }
                            }
                            break;
                        case 3://依据比例退回
                            int backCount = 0;
                            foreach (var step in steps)
                            {
                                if (IsBack(step, executeModel.FlowID, currentTask.GroupID, currentTask.PrevID, currentTask.Sort))
                                {
                                    backCount++;
                                }
                            }
                            isBack = (((decimal)backCount / (decimal)steps.Count) * 100).Round() >= (countersignatureStep.Behavior.CountersignaturePercentage <= 0 ? 100 : countersignatureStep.Behavior.CountersignaturePercentage);
                            break;
                    }

                    if (isBack)
                    {
                        var tjTasks = GetTaskList(currentTask.ID, false);
                        foreach (var tjTask in tjTasks)
                        {
                            if (tjTask.ID == currentTask.ID || tjTask.Status.In(2, 3, 4, 5))
                            {
                                continue;
                            }
                            Completed(tjTask.ID, "", false, 5);
                        }
                    }
                }
                #endregion

                //如果退回步骤是子流程步骤，则要作废子流程实例
                if (currentStep.type == "subflow" && currentStep.subflow.IsGuid() && currentTask.SubFlowGroupID.HasValue)
                {
                    DeleteInstance(currentStep.subflow.ToGuid(), currentTask.SubFlowGroupID.Value, true);
                }

                if (isBack)
                {
                    var backTaskList = tasks.Distinct();
                    if (backTaskList.Count() == 0)
                    {
                        Completed(currentTask.ID, "", false, 0, "");
                        result.DebugMessages += "没有接收人,退回失败!";
                        result.IsSuccess = false;
                        result.Messages += "没有接收人,退回失败!";
                        result.NextTasks = nextTasks;
                        scope.Complete();
                        return;
                    }

                    foreach (var task in backTaskList)
                    {
                        if (task != null)
                        {
                            //删除抄送
                            if (task.Type == 5)
                            {
                                WorkFlowTaskDal.Instance.Delete(task.ID);
                                continue;
                            }

                            WorkFlowTask newTask = task;
                            newTask.ID = Guid.NewGuid();
                            newTask.PrevID = currentTask.ID;
                            newTask.Note = "退回任务";
                            newTask.ReceiveTime = DateTime.Now;
                            newTask.SenderID = currentTask.ReceiveID;
                            newTask.SenderName = currentTask.ReceiveName;
                            newTask.SenderTime = DateTime.Now;
                            newTask.Sort = currentTask.Sort + 1;
                            newTask.Status = 0;
                            newTask.Type = 4;
                            newTask.Comment = "";
                            newTask.OpenTime = null;
                            //newTask.PrevStepID = currentTask.StepID;

                            if (currentStep.workTime != "")
                            {
                                double gs; double.TryParse(currentStep.workTime, out gs);
                                newTask.CompletedTime = DateTime.Now.AddHours(gs);
                                // = DateTime.Now.AddHours((double)currentStep.workTime);
                            }
                            else
                            {
                                newTask.CompletedTime = null;
                            }
                            newTask.CompletedTime1 = null;
                            WorkFlowTaskDal.Instance.Insert(newTask);
                            nextTasks.Add(newTask);
                        }
                    }

                    //删除临时任务
                    var nextSteps = WorkFlowBll.Instance.GetNextSteps(executeModel.FlowID, executeModel.StepID);
                    foreach (var step in nextSteps)
                    {
                        WorkFlowTaskDal.Instance.DeleteTempTasks(currentTask.FlowID, step.ID, currentTask.GroupID,
                            IsCountersignature ? Guid.Empty : currentStep.id.ToGuid()
                            );
                    }
                }

                scope.Complete();
            }

            if (nextTasks.Count > 0)
            {
                List<string> nextStepName = new List<string>();
                foreach (var nstep in nextTasks)
                {
                    nextStepName.Add(nstep.StepName);
                }
                string msg = string.Format("已退回到:{0}", nextStepName.Distinct().ToArray().Join1(","));
                result.DebugMessages += msg;
                result.IsSuccess = true;
                result.Messages += msg;
                result.NextTasks = nextTasks;
            }
            else
            {
                result.DebugMessages += "已退回,等待其它步骤处理";
                result.IsSuccess = true;
                result.Messages += "已退回,等待其它步骤处理";
                result.NextTasks = nextTasks;
            }
            return;
        }

        /// <summary>
        /// 保存任务
        /// </summary>
        /// <param name="executeModel"></param>
        private void executeSave(Execute executeModel)
        {
            //如果是第一步提交并且没有实例则先创建实例
            WorkFlowTask currentTask = null;
            bool isFirst = executeModel.StepID == wfInstalled.FirstStepID && executeModel.TaskID == Guid.Empty && executeModel.GroupID == Guid.Empty;
            if (isFirst)
            {
                currentTask = createFirstTask(executeModel);
            }
            else
            {
                currentTask = WorkFlowTaskDal.Instance.Get(executeModel.TaskID);
            }
            if (currentTask == null)
            {
                result.DebugMessages = "未能创建或找到当前任务";
                result.IsSuccess = false;
                result.Messages = "未能创建或找到当前任务";
                return;
            }
            else if (currentTask.Status.In(2, 3, 4))
            {
                result.DebugMessages = "当前任务已处理";
                result.IsSuccess = false;
                result.Messages = "当前任务已处理";
                return;
            }
            else
            {
                currentTask.InstanceID = executeModel.InstanceID;
                nextTasks.Add(currentTask);
                if (isFirst)
                {
                    currentTask.Title = executeModel.Title.IsNullOrEmpty() ? "未命名任务" : executeModel.Title;
                    WorkFlowTaskDal.Instance.Update(currentTask);
                }
                else
                {
                    if (!executeModel.Title.IsNullOrEmpty())
                    {
                        currentTask.Title = executeModel.Title;
                        WorkFlowTaskDal.Instance.Update(currentTask);
                    }
                }
            }

            result.DebugMessages = "保存成功";
            result.IsSuccess = true;
            result.Messages = "保存成功";
        }

        /// <summary>
        /// 完成任务
        /// </summary>
        /// <param name="executeModel"></param>
        /// <param name="isCompleteTask">是否需要调用Completed方法完成当前任务</param>
        private void executeComplete(Execute executeModel, bool isCompleteTask = true)
        {
            if (executeModel.TaskID == Guid.Empty || executeModel.FlowID == Guid.Empty)
            {
                result.DebugMessages = "完成流程参数错误";
                result.IsSuccess = false;
                result.Messages = "完成流程参数错误";
                return;
            }
            var task = WorkFlowTaskDal.Instance.Get(executeModel.TaskID);
            if (task == null)
            {
                result.DebugMessages = "未找到当前任务";
                result.IsSuccess = false;
                result.Messages = "未找到当前任务";
                return;
            }
            else if (isCompleteTask && task.Status.In(2, 3, 4))
            {
                result.DebugMessages = "当前任务已处理";
                result.IsSuccess = false;
                result.Messages = "当前任务已处理";
                return;
            }
            if (isCompleteTask)
            {
                Completed(task.ID, executeModel.Comment, executeModel.IsSign);
            }

            #region 更新业务表标识字段的值为1
            if (wfInstalled.titleField != null && wfInstalled.titleField.link.ToGuid() != Guid.Empty && !wfInstalled.titleField.table.IsNullOrEmpty()
                && !wfInstalled.titleField.field.IsNullOrEmpty() && wfInstalled.databases.Count() > 0)
            {
                var firstDB = wfInstalled.databases.First();
                try
                {
                    WorkFlowTaskDal.UpTabel(task.Urls, wfInstalled.titleField.field, "1", firstDB.primaryKey, task.InstanceID);
                }
                catch (Exception x)
                {

                }

            }
            #endregion

            #region 执行子流程完成后事件
            var parentTasks = GetBySubFlowGroupID(task.GroupID);
            if (parentTasks.Count > 0)
            {
                var parentTask = parentTasks.First();
                var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(executeModel.FlowID);
                string error = "";
                var flowRunModel = WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);
                //   var flowRunModel = GetWorkFlowRunModel(parentTask.FlowID);
                if (flowRunModel != null)
                {
                    var steps = flowRunModel.Steps.Where(p => p.ID == parentTask.StepID);
                    if (steps.Count() > 0 && !steps.First().Event.SubFlowCompletedBefore.IsNullOrEmpty())
                    {
                        ExecuteFlowCustomEvent(steps.First().Event.SubFlowCompletedBefore.Trim(), new WorkFlowCustomEventParams()
                        {
                            FlowID = parentTask.FlowID,
                            GroupID = parentTask.GroupID,
                            InstanceID = parentTask.InstanceID,
                            StepID = parentTask.StepID,
                            TaskID = parentTask.ID
                        });
                    }
                }
            }
            #endregion

            result.DebugMessages += "已完成";
            result.IsSuccess = true;
            result.Messages += "已完成";
        }

        /// <summary>
        /// 转交任务
        /// </summary>
        /// <param name="executeModel"></param>
        private void executeRedirect(Execute executeModel)
        {
            WorkFlowTask currentTask = WorkFlowTaskDal.Instance.Get(executeModel.TaskID);
            if (currentTask == null)
            {
                result.DebugMessages = "未能创建或找到当前任务";
                result.IsSuccess = false;
                result.Messages = "未能创建或找到当前任务";
                return;
            }
            else if (currentTask.Status.In(2, 3, 4, 5))
            {
                result.DebugMessages = "当前任务已处理";
                result.IsSuccess = false;
                result.Messages = "当前任务已处理";
                return;
            }
            else if (currentTask.Status == -1)
            {
                result.DebugMessages = "当前任务正在等待他人处理";
                result.IsSuccess = false;
                result.Messages = "当前任务正在等待他人处理";
                return;
            }
            if (executeModel.Steps.First().Value.Count == 0)
            {
                result.DebugMessages = "未设置转交人员";
                result.IsSuccess = false;
                result.Messages = "未设置转交人员";
                return;
            }
            string receiveName = currentTask.ReceiveName;
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                foreach (var user in executeModel.Steps.First().Value)
                {
                    currentTask.ID = Guid.NewGuid();
                    currentTask.ReceiveID = user.ID;
                    currentTask.ReceiveName = user.Name;
                    currentTask.OpenTime = null;
                    currentTask.Status = 0;
                    currentTask.IsSign = 0;
                    currentTask.Type = 3;
                    currentTask.Note = string.Format("该任务由{0}转交", receiveName);
                    if (!HasNoCompletedTasks(currentTask.FlowID, currentTask.StepID, currentTask.GroupID, user.ID))
                    {
                        WorkFlowTaskDal.Instance.Insert(currentTask);
                    }
                    WorkFlowTaskDal.Instance.Insert(currentTask);
                    //  nextTasks.Insert(currentTask);
                }
                Completed(executeModel.TaskID, executeModel.Comment, executeModel.IsSign, 2, "已转交他人处理");

            }
            List<string> nextStepName = new List<string>();
            foreach (var user in executeModel.Steps.First().Value)
            {
                nextStepName.Add(user.Name);
            }
            string userName = nextStepName.Distinct().ToArray().Join1(",");
            result.DebugMessages = string.Concat("已转交给:", userName);
            result.IsSuccess = true;
            result.Messages = string.Concat("已转交给:", userName);
            return;
        }

        /// <summary>
        /// 创建第一个任务
        /// </summary>
        /// <param name="executeModel"></param>
        /// <param name="isSubFlow">是否是创建子流程任务</param>
        /// <returns></returns>
        private WorkFlowTask createFirstTask(Execute executeModel, bool isSubFlow = false)
        {
            if (wfInstalled == null || isSubFlow)
            {
                var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(executeModel.FlowID);
                string error = "";
                wfInstalled = wfl.runjson;//WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);
            }

            var nextSteps = wfInstalled.steps.Where(p => p.id == wfInstalled.FirstStepID.ToString());
            if (nextSteps.Count() == 0)
            {
                return null;
            }
            WorkFlowTask task = new WorkFlowTask();

            //if (nextSteps.First().workTime > 0)
            //{
            if (nextSteps.First().workTime != "")
            {
                double gs; double.TryParse(nextSteps.First().workTime, out gs);
                // newTask.CompletedTime = DateTime.Now.AddHours(gs);
                task.CompletedTime = DateTime.Now.AddHours(gs);
            }
            task.FlowID = executeModel.FlowID;
            task.GroupID = Guid.NewGuid();
            task.ID = Guid.NewGuid();
            task.Type = 0;
            task.InstanceID = executeModel.InstanceID;
            if (!executeModel.Note.IsNullOrEmpty())
            {
                task.Note = executeModel.Note;
            }
            task.PrevID = Guid.Empty;
            task.PrevStepID = Guid.Empty;
            task.ReceiveID = executeModel.Sender.ID;
            task.ReceiveName = executeModel.Sender.Name;
            task.ReceiveTime = DateTime.Now;
            task.SenderID = executeModel.Sender.ID;
            task.SenderName = executeModel.Sender.Name;
            task.SenderTime = task.ReceiveTime;
            task.Status = 0;
            task.StepID = wfInstalled.FirstStepID;
            task.StepName = nextSteps.First().name;
            task.Sort = 1;
            task.Title = executeModel.Title.IsNullOrEmpty() ? "(" + wfInstalled.name + ")" : executeModel.Title;
            task.Urls = wfInstalled.databases.First().table;
            WorkFlowTaskDal.Instance.Insert(task);
            if (isSubFlow)
            {
                wfInstalled = null;
            }
            return task;
        }
        /// <summary>
        /// 判断实例是否已完成
        /// </summary>
        /// <param name="groupID"></param>
        /// <returns></returns>
        public bool GetInstanceIsCompleted(Guid flowID, Guid groupID)
        {
            var tasks = WorkFlowTaskDal.Instance.GetList("select *from WorkFlowTask where flowID=@flowID and groupID=@groupID", new { flowID = flowID, groupID = groupID }).ToList();
            return tasks.Find(p => p.Status.In(0, 1)) == null;
        }
        /// <summary>
        /// 完成一个任务
        /// </summary>
        /// <param name="taskID"></param>
        /// <param name="comment"></param>
        /// <param name="isSign"></param>
        /// <returns></returns>
        public int Completed(Guid taskID, string comment = "", bool isSign = false, int status = 2, string note = "")
        {

            var task = WorkFlowTaskDal.Instance.Get(taskID);
            if (task != null)
            {
                task.CompletedTime1 = System.DateTime.Now;
                task.Comment = comment;
                task.IsSign = isSign ? 0 : 1;
                task.Status = status;
                task.Note = note;
                return WorkFlowTaskDal.Instance.Update(task);
            }
            return 0;
        }
        /// <summary>
        /// 得到一个流程实例一个步骤的任务
        /// </summary>
        /// <param name="flowID"></param>
        /// <param name="groupID"></param>
        /// <returns></returns>
        public List<WorkFlowTask> GetTaskList(Guid flowID, Guid stepID, Guid groupID)
        {
            return WorkFlowTaskDal.Instance.GetList("select *from WorkFlowTask where flowID=@flowID and stepID=@stepID and groupID=@groupID", new { flowID = flowID, stepID = stepID, groupID = groupID }).ToList();
        }
        /// <summary>
        /// 得到和一个任务同级的任务
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="isStepID">是否区分步骤ID，多步骤会签区分的是上一步骤ID</param>
        /// <returns></returns>
        public List<WorkFlowTask> GetTaskList(Guid taskID, bool isStepID = true)
        {
            var task = WorkFlowTaskDal.Instance.Get(taskID);
            if (task == null)
            {
                return null;
            }
            string sql = string.Format("SELECT * FROM WorkFlowTask WHERE PrevID=@PrevID AND {0}", isStepID ? "StepID=@StepID" : "PrevStepID=@StepID");

            return WorkFlowTaskDal.Instance.GetList(sql, new { PrevID = task.PrevID, StepID = isStepID ? task.StepID : task.PrevStepID }).ToList();


        }

        /// <summary>
        /// 得到一个实例的任务
        /// </summary>
        /// <param name="flowID"></param>
        /// <param name="groupID"></param>
        /// <returns></returns>
        public List<WorkFlowTask> GetTaskList(Guid flowID, Guid groupID)
        {
            if (flowID != null || flowID.IsEmptyGuid())
            {
                return WorkFlowTaskDal.Instance.GetList("select * from WorkFlowTask where groupID=@groupID", new { groupID = groupID }).ToList();
            }
            else
            {
                return WorkFlowTaskDal.Instance.GetList("select * from WorkFlowTask where groupID=@groupID and flowID=@flowID", new { groupID = groupID, flowID = flowID }).ToList();
            }

        }
        /// <summary>
        /// 创建临时任务（待办人员看不到）
        /// </summary>
        /// <param name="executeModel"></param>
        private List<WorkFlowTask> createTempTasks(Execute executeModel, WorkFlowTask currentTask)
        {
            List<WorkFlowTask> tasks = new List<WorkFlowTask>();
            foreach (var step in executeModel.Steps)
            {
                foreach (var user in step.Value)
                {
                    var nextSteps = wfInstalled.steps.Where(p => p.id == step.Key.ToString());
                    if (nextSteps.Count() == 0)
                    {
                        continue;
                    }
                    var nextStep = nextSteps.First();
                    WorkFlowTask task = new WorkFlowTask();
                    if (nextStep.workTime != "")
                    {
                        double gs;
                        double.TryParse(nextStep.workTime, out gs);
                        task.CompletedTime = DateTime.Now.AddHours(gs);
                    }
                    task.FlowID = executeModel.FlowID;
                    task.GroupID = currentTask != null ? currentTask.GroupID : executeModel.GroupID;
                    task.ID = Guid.NewGuid();
                    task.Type = 0;
                    task.InstanceID = executeModel.InstanceID;
                    if (!executeModel.Note.IsNullOrEmpty())
                    {
                        task.Note = executeModel.Note;
                    }
                    task.PrevID = currentTask.ID;
                    task.PrevStepID = currentTask.StepID;
                    task.ReceiveID = user.ID;
                    task.ReceiveName = user.Name;
                    task.ReceiveTime = DateTime.Now;
                    task.SenderID = executeModel.Sender.ID;
                    task.SenderName = executeModel.Sender.Name;
                    task.SenderTime = task.ReceiveTime;
                    task.Status = -1;
                    task.StepID = step.Key;
                    task.StepName = nextStep.name;
                    task.Sort = currentTask.Sort + 1;
                    task.Title = executeModel.Title.IsNullOrEmpty() ? currentTask.Title : executeModel.Title;

                    if (!HasNoCompletedTasks(executeModel.FlowID, step.Key, currentTask.GroupID, user.ID))
                    {
                        WorkFlowTaskDal.Instance.Insert(task);
                    }
                    // WorkFlowTaskDal.Instance.Insert(task);
                    // tasks.Add(task);
                }
            }
            return tasks;
        }
        /// <summary>
        /// 查询一个用户在一个步骤是否有未完成任务
        /// </summary>
        /// <param name="flowID"></param>
        /// <returns></returns>
        public bool HasNoCompletedTasks(Guid flowID, Guid stepID, Guid groupID, Guid userID)
        {
            var tasks = WorkFlowTaskDal.Instance.GetList("select *from WorkFlowTask where flowID=@flowID and groupID=@groupID and stepID=@stepID and ReceiveID=@userID", new { flowID = flowID, groupID = groupID, stepID = stepID, userID = userID }).ToList();
            return tasks.Find(p => p.Status.In(0, 1)) == null;
        }


        /// <summary>
        /// 判断一个步骤是否通过
        /// </summary>
        /// <param name="step"></param>
        /// <param name="groupID"></param>
        /// <returns></returns>
        private bool IsPassing(Step step, Guid flowID, Guid groupID, Guid taskID, int sort)
        {
            var tasks = GetTaskList(flowID, step.ID, groupID).FindAll(p => p.Sort == sort && p.Type != 5);
            if (tasks.Count == 0)
            {
                return false;
            }
            bool isPassing = true;
            switch (step.Behavior.HanlderModel)
            {
                case 0://所有人必须处理
                case 3://独立处理
                    isPassing = tasks.Where(p => p.Status != 2).Count() == 0;
                    break;
                case 1://一人同意即可
                    isPassing = tasks.Where(p => p.Status == 2).Count() > 0;
                    break;
                case 2://依据人数比例
                    isPassing = (((decimal)(tasks.Where(p => p.Status == 2).Count() + 1) / (decimal)tasks.Count) * 100).Round() >= (step.Behavior.Percentage <= 0 ? 100 : step.Behavior.Percentage);
                    break;
            }
            return isPassing;
        }

        /// <summary>
        /// 判断一个步骤是否退回
        /// </summary>
        /// <param name="step"></param>
        /// <param name="groupID"></param>
        /// <returns></returns>
        private bool IsBack(Step step, Guid flowID, Guid groupID, Guid taskID, int sort)
        {
            var tasks = GetTaskList(flowID, step.ID, groupID).FindAll(p => p.Sort == sort && p.Type != 5);
            if (tasks.Count == 0)
            {
                return false;
            }
            bool isBack = true;
            switch (step.Behavior.HanlderModel)
            {
                case 0://所有人必须处理
                case 3://独立处理
                    isBack = tasks.Where(p => p.Status.In(3, 5)).Count() > 0;
                    break;
                case 1://一人同意即可
                    isBack = tasks.Where(p => p.Status.In(2, 4)).Count() == 0;
                    break;
                case 2://依据人数比例
                    isBack = (((decimal)(tasks.Where(p => p.Status.In(3, 5)).Count() + 1) / (decimal)tasks.Count) * 100).Round() >= 100 - (step.Behavior.Percentage <= 0 ? 100 : step.Behavior.Percentage);
                    break;
            }
            return isBack;
        }
        int UpdateTempTasks(Guid flowID, Guid stepID, Guid groupID, DateTime? completedTime, DateTime receiveTime)
        {
            string sql = "UPDATE WorkFlowTask SET CompletedTime=@CompletedTime,ReceiveTime=@ReceiveTime,SenderTime=@SenderTime,Status=0 WHERE FlowID=@FlowID AND StepID=@StepID AND GroupID=@GroupID AND Status=-1";
            //SqlParameter[] parameters = new SqlParameter[]{
            //     !completedTime.HasValue ? new SqlParameter("@CompletedTime", SqlDbType.DateTime) { Value = DBNull.Value } :
            //     new SqlParameter("@CompletedTime", SqlDbType.DateTime) { Value =  },
            //     new SqlParameter("@ReceiveTime", SqlDbType.DateTime){ Value = receiveTime },
            //     new SqlParameter("@SenderTime", SqlDbType.DateTime){ Value = receiveTime },
            //     new SqlParameter("@FlowID", SqlDbType.UniqueIdentifier){ Value = flowID },
            //     new SqlParameter("@StepID", SqlDbType.UniqueIdentifier){ Value = stepID },
            //     new SqlParameter("@GroupID", SqlDbType.UniqueIdentifier){ Value = groupID }
            // };
            var da = WorkFlowTaskDal.Instance.Get(new
            {
                FlowID = flowID,
                StepID = stepID,
                GroupID = groupID
            });
            if (da != null)
            {
                da.CompletedTime = null;
                da.ReceiveTime = System.DateTime.Now;
                da.SenderTime = receiveTime;
                return WorkFlowTaskDal.Instance.Update(da);
            }
            return 0;
            //return Asxsyd92Core.Utils.Data.DbUtils.ExecuteNonQuerySp(sql, null);
        }

        /// <summary>
        /// 删除流程实例
        /// </summary>
        /// <param name="flowID"></param>
        /// <param name="groupID"></param>
        /// <returns></returns>
        public int DeleteInstance(Guid flowID, Guid groupID, bool hasInstanceData = false)
        {
            if (hasInstanceData)
            {
                var tasks = GetTaskList(flowID, groupID);
                if (tasks.Count > 0 && !tasks.First().InstanceID.IsNullOrEmpty())
                {
                    var wfl = WebOS.Dal.WorkFlowDal.Instance.Get(flowID);
                    string error = "";
                    var wfRunModel = WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON, out error);
                    if (wfRunModel != null && wfRunModel.DataBases.Count() > 0)
                    {
                        var dataBase = wfRunModel.DataBases.First();
                        WorkFlowTaskDal.DeleteTabel(dataBase.Table, dataBase.PrimaryKey, tasks.First().InstanceID);
                    }
                }
            }


            return WorkFlowTaskDal.DeleteInstance(flowID, groupID);
        }

        /// <summary>
        /// 根据subflow得到一个任务
        /// </summary>
        /// <param name="subflowGroupID"></param>
        /// <returns></returns>
        public List<WorkFlowTask> GetBySubFlowGroupID(Guid subflowGroupID)
        {
            string sql = "SELECT * FROM WorkFlowTask WHERE SubFlowGroupID=@SubFlowGroupID";
            return WorkFlowTaskDal.Instance.GetList(sql, new { SubFlowGroupID = subflowGroupID }).ToList();
        }

    }
}
